<template>
	<view>
		<view class="back-btn goback" @click="goback">
		  <text class="cuIcon cuIcon-back text-white"></text>
		</view>
		<view class="selectclass">
			<text class="select-label">请选择你要查询的班级:</text>
			<picker @change="bindPickerChange" @click="isActive = true" @cancel="isActive = false" :value="index" :range="array" :disabled="!array || array.length===0">
				<view class="picker" :class="{ active: isActive }">
					{{array[index]}}
			    </view>
			</picker>
		</view>
		<!-- 课表展示 -->
		<view class="table-container" v-if="courseList.length>0">
			<table class="table">
				<thead>
		    		<tr class="tr">
		    			<th class="th">时间</th>
		    			<th v-for="(day,index) in timelist" :key="index" class="th">{{day}}</th>
		    		</tr>
		    	</thead>
				<tbody>
		    		<tr v-for="(timeSlot, timeIndex) in timeSlots" :key="timeIndex" class="tr">
		    			<td class="td">{{timeSlot}}</td>
		    			<td v-for="(day, dayIndex) in timelist" :key="dayIndex" class="td">
		    				<view v-for="(course, courseIndex) in getCourseByDayAndTime(day, timeSlot)" :key="course.classId" class="classitem">
		    					{{course.courseName}}
		    				</view>
		    			</td>
		    		</tr>
		    	</tbody>
		    </table>
		</view>
		
		<!-- 文件上传 -->
		<view class="uploadfile" v-else>
			<view class="upload-tips">
				<text>请上传该班级的课表Excel文件</text>
				<text class="tip-small">(支持.xlsx、.xls格式)</text>
		    </view>
			<view class="upload-btn " @click="chooseFile">
				<text>选择文件</text>
				<text class="cuIcon cuIcon-file"></text>
			</view>
			<view class="file-info" v-if="selectedFile">
			    已选择: {{selectedFile.name}}
			</view>
			<button 
		        class="submit-btn" 
		        :disabled="!selectedFile || uploading"
		        @click="uploadFile">
				确认上传
			</button>
		</view>
	</view>
</template>

<script>
	import { getCourseList } from '../../api/class'
	import { importCourse } from '../../api/class'
	export default {
		data() {
			return {
				//路由传参当前老师所创建的所有班级
				array: [], //创建的班级名称
				index: 0,
				isActive:false,
				timelist: ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"],
				timeSlots: ["第1，2节", "第3，4节", "第5，6节", "第7，8节", "第9，10节"],
				courseList: [],  //课表的信息
				classlist:uni.getStorageSync('classlist')||[], //创建的班级所有信息
				selectedFile:null,
				uploading:false,
			}
		},
		onLoad() {
			if(!this.classlist||this.classlist.length===0){
				uni.showToast({
					title:'未创建班级，无法查询课表',
					icon:'none',
					duration:2000
				})
				this.array=[]
				return
			}
			this.array = this.classlist.map(item => item.class_name || '未知班级')
			console.log('生成的array:', this.array)
			this.getcourselist()
		},
		onShow() {
			//检查登录状态
			const userInfo = uni.getStorageSync('userInfo')
			if (!userInfo) {
				uni.redirectTo({ url: '/pages/login/login' })
				return
			}
		},
		methods: {
			//返回
			goback(){
				uni.navigateBack()
			},
			
			// 根据星期和时间获取课程
			getCourseByDayAndTime(day, time) {
				return this.courseList.filter(course => 
					course.day === day && course.time === time
				);
			},
			
			//获取当前要查询的班级,点击确认的时候就可以查询课表
		    bindPickerChange(e) {
				this.isActive = false
				this.index = e.detail.value
				this.getcourselist()
			},
			
			//选择文件
			chooseFile(){
				// 微信小程序不支持uni.chooseFile，后面改
				uni.chooseFile({
					count: 1,
					type: 'file',
					extension:['.xlsx','.xls'],
					success: (res) => {
						const file=res.tempFiles[0];
						const fileExt = file.name.split('.').pop().toLowerCase();//检测文件的类型
						if(!['xlsx','xls'].includes(fileExt)){
							uni.showToast({
								title:'请上传.xlsx或.xls格式文件',
								icon:'none',
								duration:2000
							})
							return 
						}
						this.selectedFile=file
						uni.showToast({ title: '已选择: ' + file.name, icon: 'none', duration:2000});
					},
					fail: (err) =>{
						uni.showToast({
							title:err.errMsg || '选取文件失败',
							icon:'none',
							duration:2000
						})
					}
				})
			},
			
			//上传文件
			async uploadFile(){
				if(!this.selectedFile){
					uni.showToast({
						title:'未选择文件,请先上传文件',
						icon:'none',
						duration:2000
					})
					return
				}
				this.uploading=true
				uni.showLoading({title:'上传中...'})
				try{
					const res=await importCourse({classId : this.classlist[this.index].id,file : this.selectedFile})
					if(res.code===200){
						uni.showToast({
							title:res.message || '文件上传成功',
							icon:'none,',
							duration:2000
						})
					}
					// this.courseList=res.data.firstCourse
					this.getcourselist();
				}catch (error) {
					uni.showToast({
						title: error.message || '上传失败',
                        icon: 'none',
						duration:2000
					});
				} finally {
					this.uploading = false;
					uni.hideLoading();
				}
			},
			
			//查询课表
			async getcourselist(){
				uni.showLoading({title:'课程表获取中...',})
				try{
					const res = await getCourseList(this.classlist[this.index].id)
					if(res.code === 200 && res.data.length>0){
						uni.showToast({
							title: res.message || '课程表获取成功',
							icon: 'success',
							duration: 2000
						})
						this.courseList = res.data
						return
					}
					if(res.code===200 && (!res.data || res.data.length === 0)){
						this.courseList=[]
						uni.showToast({
							title:'未查询到该班级的课表，请上传该班级课表的excel文件',
							icon:'none',
							duration:2000
						})
					}
				}catch(error){
					uni.showToast({
						title: error.message || '课表获取失败',
						icon: 'none',
						duration: 2000
					})
					this.courseList=[]
				}finally{
					uni.hideLoading();
				}
			}
		}
	}
</script>

<style>
	@import url("css/timeable.css");
	@import url("../../components/watch-login/css/icon.css");
</style>